import Taro from '@tarojs/taro'
import React, { PureComponent } from 'react'
import { View, Input, Image } from '@tarojs/components'
import Images from '@ASSET/Images'
import { Analytic_Type } from '@CONSTANTS/analytic'
import SearchPredictions from './SearchPredictions'
import './SearchInput.scss'

export default class SearchInput extends PureComponent {
  state = {
    language: 'zh',
    st: this.props.value || '',
    showPredictions: this.props.showPredictions
  }

  onInput = e => {
    const { showPredictions } = this.props
    const text = e.detail.value
    this.setState({
      st: text,
      showPredictions,
    })
  }

  onClear = () => {
    const { page } = this.props
    page && Taro.tracker.trackEvent(Analytic_Type.tap_input_delete.eventId, { Page: page })
    this.setState({
      st: ''
    })
  }

  onConfirm = e => {
    const text = e.detail.value
    this.onSearch(text)
  }

  onSearch = st => {
    const { onSearch } = this.props
    this.setState({
      showPredictions: false,
    })
    onSearch?.(st)
  }

  onClickPrediction = st => {
    const { onClickPrediction } = this.props
    this.setState({
      st,
      showPredictions: false,
    })
    onClickPrediction(st)
  }

  render() {
    const {
      language,
      st,
      showPredictions,
    } = this.state
    const {
      autoFocus,
      placeholder,
      showClear
    } = this.props
    const showClearBtn = showClear && !!st
    return (
      <View className="search-input">
        <View className="search-input-container">
          <Image src={Images.search} className="search-icon" />
          <Input
            placeholder={placeholder}
            placeholderClass="input-placeholder"
            className="input"
            focus={autoFocus}
            confirmType="search"
            onConfirm={this.onConfirm}
            onInput={this.onInput}
            value={st}
          />
          {showClearBtn && (
            <View className="search-delete-container" onClick={this.onClear}>
              <Image src={Images.icon_grey_delete} className="search-delete" />
            </View>
          )}
        </View>
        <SearchPredictions
          st={st}
          showPredictions={showPredictions}
          language={language}
          onClickPrediction={this.onClickPrediction}
        />
      </View>
    )
  }
}
